﻿using ChangingValidationFromAndbyAggregate.Dominio;
using NHibernate.Validator.Cfg.Loquacious;

namespace ChangingValidationFromAndbyAggregate.Validators
{
    public class InvoiceValidation : ValidationDef<Invoice>
    {
        public InvoiceValidation()
        {
            ValidateInstance.By((invoice, validationContext) =>
                                    {
                                        bool isValid = true;

                                        // When a Customer is used to emit an Invoice, the Customer must have a Italian’s Patita-IVA
                                        if (invoice.Customer != null &&
                                            string.IsNullOrEmpty(invoice.Customer.VatIdentificationNumber))
                                        {
                                            isValid = false;
                                            validationContext.AddInvalid<Customer, string>(
                                                "To be used in an invoice the Customer should have the VatNumber",
                                                p => p.VatIdentificationNumber);
                                        }

                                        return isValid;
                                    });

            // The invoice must have a valid Customer
            Define(e => e.Customer).IsValid().And.NotNullable();
        }
    }
}
